// pages/nearby/nearby.js
const app = getApp();
const API = require('../../common/constant');
const util = require('../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rule: '筛选',
    isChoose: false,
    eventTitle: "",
    toChooseCity: false,
    pageIndex: 1,
    pageCount: 0,
    activity: [],
    sex: ""
  },
  //搜索框筛选
  searchByTitle: function (e) {
    console.log(e.detail.value);
    this.setData({
      activity: [],
      pageIndex: 1,
      eventTitle: e.detail.value
    })
    this.getActivities();
  },
  //打开筛选框
  openChooseRule: function () {
    this.setData({
      isChoose: true
    })
  },
  closeRule: function () {
    this.setData({
      isChoose: false
    })
  },
  // 筛选结束
  closeChooseRule: function (e) {
    let rule = '';
    if (e.currentTarget.dataset.num === '1') {
      rule = '男'
    } else if (e.currentTarget.dataset.num === '2') {
      rule = '女'
    } else {
      rule = '不限'
    }
    this.setData({
      isChoose: false,
      sex: e.currentTarget.dataset.num,
      activity: [],
      pageIndex: 1,
      rule: rule
    })
    this.getActivities();
  },
  getNowCity: function () {
    let QQMapWX = app.getQQMap();
    const qqmapsdk = new QQMapWX({
      key: 'LBOBZ-AFKCX-SDS4Z-7OY56-CPLTJ-DGBMU'
    });
    let that = this;
    let mylocal = app.getMyLocaltion();
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: mylocal.latitude,
        longitude: mylocal.longitude
      },
      success: function (res) {
        console.log("获取用户位置信息:", res);
        let city = res.result.address_component.city;
        let cityCode = res.result.ad_info.city_code.slice(3)
        if (app.globalData.chooseCity) {
          that.setData({
            ['search.city']: app.globalData.chooseCity,
            cityCode: app.globalData.chooseCityCode
          })
        } else {
          that.setData({
            ['search.city']: city,
            cityCode: cityCode
          })
        }
        that.getActivities();
      },
      fail: function (res) {
      }
    });
  },

  getActivities: function () {
    let myLocal = app.getMyLocaltion();
    wx.showLoading({
      title: '正在加载'
    })
    util.http({
      url: API.URL.EVENT.FIND_EVENTINFOBYPAGE,
      data: {
        pageIndex: this.data.pageIndex,
        pageSize: 4,
        cityCode: this.data.cityCode + "",
        longitude: myLocal.longitude,
        latitude: myLocal.latitude,
        sex: this.data.sex,
        eventTitle: this.data.eventTitle,
        status: 'true'
      },
      success: (res) => {
        console.log("请求的数据为:", res)
        wx.hideLoading();
        wx.stopPullDownRefresh();
        this.changeActivities(res.data);
        this.setData({
          isPullDown: false
        })
      },
      fail: (res) => {
        console.log(res);
        wx.showToast({
          title: '获取不到活动信息',
          icon: "none",
          duration: 2000
        })
        this.setData({
          isPullDown: false
        })
      }
    })
  },
  /* 更改activities*/
  changeActivities: function (params) {
    params.bussData.map((item, index) => {
      if (item.eventType == "chat") {
        item.activityType = "#解闷聊天#";
        item.activityColor = '#F4BC11';
      } else if (item.eventType == "partner") {
        item.activityType = "#美食搭伙#";
        item.activityColor = '#FF8023';
      } else if (item.eventType == 'find') {
        item.activityType = "#求邂逅#";
        item.activityColor = '#FE3232';
      }
    });
    this.setData({
      activity: this.data.activity.concat(params.bussData),
      // activity: params.bussData,
      pageCount: params.pageCount
    })
    console.log('总页数为:', params.pageCount)
  },


  toFanInformation: function (e) {
    let id = e.currentTarget.id;
    let num = e.currentTarget.dataset.num;
    let distance = this.data.activity[num].distance;
    let sesssionID = wx.getStorageSync("sessionId");
    if (sesssionID.length == 0) {
      wx.showToast({
        title: '您还没有登录，不能查看活动详情，2s后自动为您跳到登录页面',
        icon: "none",
        duration: 2000
      });
      setTimeout(function () {
        wx.navigateTo({
          url: '../loginAndRegister/loginAndRegister'
        });
      }, 2000)
    } else {
      if (this.data.activity[num].userId == wx.getStorageSync('userInfo').userId) {
        wx.navigateTo({
          url: `../myPublishEventInfo/myPublishEventInfo?id=${id}`
        });
      } else {
        wx.navigateTo({
          url: `../FanInfo/FanInfo?id=${id}`
        });
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (!app.globalData.hasUserInfo) {
      return;
    }
    this.getNowCity();
    app.globalData.isNewNearBy = false;
  },

  onShow: function () {
    if (!app.globalData.hasUserInfo){
      app.showUserInfo('请授权，2s后自动跳转首页', 'none', 2000);
      setTimeout(function(){
        wx.switchTab({
          url: '../index/index'
        })
      },2000)
      return;
    }
    if (app.globalData.isNewNearBy) {
      this.setData({
        activity: [],
        pageIndex: 1
      })
      this.getNowCity();
      console.log(app.globalData.isNewNearBy);
      app.globalData.isNewNearBy = false;
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.isPullDown) {
      return
    }
    this.setData({
      activity: [],
      pageIndex: 1
    })
    this.getActivities();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.scrollShow) return;
    if (this.data.pageCount <= this.data.pageIndex) return
    this.data.pageIndex++;
    this.getActivities()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})